import React, { PureComponent } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Card, Popconfirm, Switch, message, Upload, Icon, Dropdown, Menu, Divider, Drawer, Button, Form, Input, Badge, Modal, Table, Descriptions, Row, Col, Select } from 'antd';
import { BaseForm, PromotionChannelsForm } from '@/components/FormTools';
import { queryChannelList, deleteData } from '@/services/auth';
import { getFundCardDetail } from '@/services/cardinfor';
import { StandardTable, SearchForm } from '@joy/joy-pro';
import { getValue, to } from '@/utils/smallTool';
import { connect } from 'dva';
import geo from '@/utils/city';
import moment from 'moment';
import authUtil from '@/utils/auth';
import styles from './index.less';
import InsureDetail from './insureDetail';

const pageInfo = { showSizeChanger: true, showQuickJumper: true, defaultPageSize: 10 };
const drawerConfig = {
  edit: {
    title: '编辑',
  },
  add: {
    title: '新增',
  },
};
const dateFormat = 'YYYY-MM-DD' || undefined;
const curDate = new Date();
const preDate = new Date(curDate.getTime());
const nextDate = new Date(curDate.getTime());
const dateStartTime = authUtil.getStartDateTime();
const drawerWidth = '70%';
const formProp = {
  labelCol: { span: 6 },
  wrapperCol: { span: 18 },
};
@connect(({ global, loading, fundinfor, authority }) => ({
  tableData: fundinfor.tableData,
  IssueChannelList: fundinfor.IssueChannelList,
  SalespersonList: fundinfor.SalespersonList,
  ManufactureList: fundinfor.ManufactureList,
  searchForm: fundinfor.searchForm,
  permissionsList: authority.permissionsList,
  tableLoading: loading.effects['fundinfor/getFundCardList'],
  watermarkConfig: global.watermarkConfig,
}))
class FundInfor extends PureComponent {
  state = {
    selectedRows: [],
    accountDetail: {},
    params: {},
    pageRequest: {
      pageNum: 1,
      pageSize: 10,
    },
    drawerStatus: {
      visible: false,
      type: 'add',
    },
    resultDate: [],
    loading: true,
    activeRecord: {},
    inputConfig: [
      {
        type: 'input',
        placeholder: '请输入用户ID',
        name: 'userId',
        label: '用户ID',
      },
      {
        type: 'input',
        placeholder: '请输入城市',
        name: 'cityCode',
        label: '城市',
      },
      {
        type: 'select',
        placeholder: '状态',
        name: 'status',
        label: '城市',
        optionData: [
          { value: '正常', name: '正常' },
          { value: '封存', name: '封存' },
          { value: '异常', name: '异常' },
          { value: '缴存', name: '缴存' },
          { value: '待缴存停缴', name: '待缴存停缴' },
          { value: '待转出停缴', name: '待转出停缴' }
        ]
      },
      {
        type: 'input',
        placeholder: '请输入姓名',
        name: 'name',
        label: '姓名'
      },
      {
        type: 'input',
        placeholder: '请输入身份证号',
        name: 'bodyCode',
        label: '身份证号',
      },
      {
        type: 'rangePicker',
        name: 'time ',
        label: '执行时间',
        format: 'YYYY-MM-DD',
        grid: { sm: 26, md: 12, xl: 8, xxl: 8 },
        defaultValue: [moment(preDate, dateFormat), moment(nextDate, dateFormat)]
      }
    ],
  };
  constructor(props) {
    super(props);
    this.$drawerForm = React.createRef();
    const { pageRequest, params } = this.state;
    this.getQueryList(params, pageRequest); //获取推广渠道列表
  }

  // 条件筛选
  /**
   * @description 条件筛选 [搜索]
   * @author zhe
   * @date 2020-04-13
   * @param {*} formData
   * @param {*} reaclData
   * @param {*} isClear
   * @memberof
   */
  actionSearch = (formData, reaclData, isClear) => {
    const params = formData;
    if (formData.insuranceTime && formData.insuranceTime.length !== 0) {
      params.jobDateStart = params.insuranceTime[0];
      params.jobDateEnd = params.insuranceTime[1];
      delete params.insuranceTime;
    }
    const pageRequest = { pageNum: 1, pageSize: 10 };
    this.setState({
      params: params,
    });
    this.getQueryList(params, pageRequest);
  };

  /**
   * @description 请求列表数据
   * @author zhe
   * @date 2020-04-13
   * @param {*} params
   * @param {*} pageRequest
   * @memberof
   */
  getQueryList = (params, pageRequest) => {
    const type = 'fundinfor/getFundCardList';
    if (!params.startTime) {
      params.startTime = moment(new Date('1970-10-11')).format('YYYY-MM-DD');
    }
    if (!params.endTime) {
      params.endTime = moment(new Date()).format('YYYY-MM-DD');
    }
    const param = Object.assign(pageRequest, params);
    const { dispatch } = this.props;
    dispatch({
      type,
      payload: param,
    });
  };

  /**
   * @description 抽屉表单提交事件
   */
  onDrawerOk = async () => {
    const { drawerStatus } = this.state;
    const { getFieldsValue, validateFields } = this.$drawerForm.current.props.form;
    const drawerItem = drawerConfig[drawerStatus.type];
    let validateError = null;
    let validateRes = null;
    [validateError, validateRes] = await to(validateFields());
    if (validateError) return false;
    let postRes = false;
    if (drawerStatus.type == 'add') {
      if (validateRes.orgId) {
        delete validateRes.orgId;
      }
    }
    validateRes.orgType = validateRes.orgType;
    delete validateRes.imgupload;
    const dataObj = await queryaddOrSaveChannel(validateRes);
    if (dataObj && dataObj.code === '000000') {
      message.success('操作成功');
      const pageRequest = { pageNum: 1, pageSize: 10 };
      this.setState({
        params: {},
      });
      this.getQueryList(this.state.params, pageRequest);
      postRes = true;
    } else {
      postRes = false;
      message.error('操作失败');
    }
    if (postRes) this.changeDrawerStatus(false);
    return true;
  };
  async getSecurityCardDetail(record) {
    const responseData = await getFundCardDetail({ accountId: record.id, userId: record.userId })
    if (responseData && responseData.code == '000000') {
      this.setState({
        accountDetail: responseData.data
      })
    }
  }
  /**
   * @description 切换抽屉状态
   * @author songs
   * @param {*} visible
   * @param {*} title
   */
  changeDrawerStatus = (visible, activeRecord = {}, event) => {
    if (visible) {
      this.getSecurityCardDetail(activeRecord);
    }
    this.setState(oldState => ({
      ...oldState,
      drawerStatus: { visible },
      activeRecord,
    }));
  };
  onHandleDelete = record => {
    const _this = this;
    this.deleteData(record).then(function () {
      const { params } = _this.state;
      const { tableData } = _this.props;
      const { pagination = {} } = tableData;
      const { pageNum, pageSize } = pagination;
      const pageRequest = { pageNum: pageNum, pageSize: pageSize };
      _this.getQueryList(params, pageRequest);
    });
  };
  tableCol = () => {
    const OptionNode = ({ record }) => (
      <div className={styles.tableButtonGroup}>
        <Button
          type="link"
          style={{ marginRight: '16px' }}
          onClick={() => {
            this.changeDrawerStatus(true, record);
          }}
        >
          明细
        </Button>
      </div>
    );
    return [
      {
        title: '用户ID',
        dataIndex: 'userId',
        width: '10%'
      },
      {
        title: '姓名',
        dataIndex: 'name',
        width: '10%',
      },
      {
        title: '缴费城市',
        dataIndex: 'cityName',
        width: '10%',
      },
      {
        title: '缴费地区',
        dataIndex: 'departmentName',
        width: '10%',
      },
      {
        title: '缴费公司',
        dataIndex: 'payCompanyName',
        width: '8%',
      },
      {
        title: '缴费基数',
        dataIndex: 'payBase',
        width: '8%',
      },
      {
        title: '账户余额',
        dataIndex: 'balance',
        width: '8%',
      },
      {
        title: '缴费明细',
        dataIndex: 'authSource5',
        width: '8%',
        render(text, record) {
          return <OptionNode record={record} />
        }
      },
      {
        title: '状态',
        dataIndex: 'fundState',
        width: '8%',

      },
      {
        title: '绑卡时间',
        dataIndex: 'boundTime',
        width: '8%',
      }
    ];
  };

  render() {
    const { tableCol, ravDrawerConfig, onDrawerOk, changeDrawerStatus, handleSelectRows } = this;
    const { drawerStatus, selectedRows, inputConfig, accountDetail } = this.state;
    const { tableLoading, watermarkConfig, tableData } = this.props;
    const { list = [], pagination = {} } = tableData;
    return (
      <div>
        <PageHeaderWrapper title="" className="hasContent">
          <div style={{ background: '#fff', padding: '20px 0px 0px 24px', marginBottom: '10px' }}>
            <SearchForm
              defaultInput={inputConfig.slice(0, 3)}
              moreInput={inputConfig.slice(3)}
              gutter={{ md: 10 }}
              useCol={{ sm: 24, md: 12, xl: 8, xxl: 8 }}
              onSearch={this.actionSearch}
            ></SearchForm>
          </div>
          <Card bordered={false}>
            <StandardTable
              isWatermark
              watermark={{ ...watermarkConfig }}
              dataSource={list}
              // showSelect
              selectedRows={selectedRows}
              pagination={{ ...pagination, ...pageInfo }}
              columns={tableCol()}
              loading={tableLoading}
              rowKey={(record, index) => index}
              // onSelectRow={this.handleSelectRows}
              onChange={($pagination, filtersArg, sorter) => {
                this.handleStandardTableChange($pagination, this.state.params, sorter, 'fundinfor/getFundCardList');
              }}
            ></StandardTable>
          </Card>
        </PageHeaderWrapper>
        <Modal
          title={`${geo.getCityNameByCode(accountDetail.payCity)}-${accountDetail.departmentName}-${accountDetail.status > 0 ? '正常' : '已解绑'}`}
          width={drawerWidth}
          destroyOnClose
          closable={false}
          onCancel={e => {
            changeDrawerStatus(false);
          }}
          onOk={e => {
            onDrawerOk();
          }}
          visible={drawerStatus.visible}
        >
          <InsureDetail accountDetail={accountDetail} />
        </Modal>
      </div>
    );
  }
}

export default FundInfor;
